import Vue from 'vue'
import Vuex from 'vuex'
import {
  STORAGE_USERINFO,
  STORAGE_ROLE,
  STORAGE_WALLETS,
  STORAGE_PARA,
  SOTRAGE_CHAINS
} from '../config/constants/storeConstants'
Vue.use(Vuex)

export function getValueInLocal(storageKey, defaultValue) {
  const storaged = localStorage.getItem(storageKey)
  if (storaged && storaged !== 'undefined') return storaged
  return defaultValue
}

export function getValueInSession(storageKey, defaultValue) {
  const storaged = sessionStorage.getItem(storageKey)
  if (storaged && storaged !== 'undefined') return storaged
  return defaultValue
}

export default new Vuex.Store({
  state: {
    // 用户信息
    userInfo: JSON.parse(getValueInSession(STORAGE_USERINFO, '{}')),
    // 用户角色
    role: getValueInSession(STORAGE_ROLE, 0),
    // 钱包列表
    wallet_list: JSON.parse(getValueInSession(STORAGE_WALLETS, '[]')),
    // Token
    token: getValueInSession('access_token', ''),
    // 平行链列表
    para_list: getValueInSession(STORAGE_PARA, []),
    // 主链列表
    main_chains: getValueInSession(SOTRAGE_CHAINS, [])
  },
  mutations: {
    // 更新角色
    updateRole(state, role) {
      state.role = role
      sessionStorage.setItem(STORAGE_ROLE, role)
    },
    // 更新用户信息
    updateUserInfo(state, info) {
      state.userInfo = info
      sessionStorage.setItem(STORAGE_USERINFO, JSON.stringify(info))
    },
    // 清楚用户数据
    clearInfo(state) {
      state.userInfo = {}
      sessionStorage.removeItem(STORAGE_USERINFO)
    },
    // 更新钱包列表
    updateWallets(state, wallets) {
      state.wallet_list = wallets
      sessionStorage.setItem(STORAGE_WALLETS, JSON.stringify(wallets))
    },
    // 更新Token
    updateToken(state, token) {
      state.token = token
      sessionStorage.setItem("access_token", token);
    },
    // 更新平行链列表
    updataParallel(state, para) {
      state.para_list = para
      sessionStorage.setItem(STORAGE_PARA, para)
    },
    // 更新主链列表
    updateMainChains(state, chains) {
      state.main_chains = chains
      sessionStorage.setItem(SOTRAGE_CHAINS, chains)
    }
  },
  actions: {

  }
})